package com.admin.utils.oss;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
@Slf4j
public class OSSUtil {
	public static String endpoint = "kuaiting.oss-cn-zhangjiakou.aliyuncs.com";
	public static String accessKeyId = "LTAI5tNUdtg4VTHGVh5EK7n2";
	public static String accessKeySecret = "WPVXQJHih1ZN1nNU56oSogGJ5Jnsfg";
	public static String bucketName = "kuaitingoss";

	public static String uploadFileToOss(String fileName, InputStream inputStream) {
		// 创建ClientConfiguration实例，您可以根据实际情况修改默认参数。
		ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
		// 设置是否支持CNAME。CNAME用于将自定义域名绑定到目标Bucket。
		conf.setSupportCname(true);
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);
		try {
			ossClient.putObject(bucketName, fileName, inputStream);
		} catch (Exception e) {

			log.error(e.getMessage());
			throw new RuntimeException("上传文件到阿里云OSS异常");
		} finally {
			ossClient.shutdown();
		}
		return "https://" + endpoint + "/" + fileName;

	}


	public static void deletFileByName(String newName) {
		// 创建ClientConfiguration实例，您可以根据实际情况修改默认参数。
		ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
		// 设置是否支持CNAME。CNAME用于将自定义域名绑定到目标Bucket。
		conf.setSupportCname(true);
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);
		try {
			ossClient.deleteObject(bucketName, newName);
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new RuntimeException("删除阿里云OSS文件异常");
		} finally {
			ossClient.shutdown();
		}
	}
}
